package com.brainshare.an.service.impl;

import java.util.List;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.brainshare.an.domain.AnMechanism;
import com.brainshare.an.domain.AnMechanismMember;
import com.brainshare.an.mapper.AnMechanismMemberMapper;
import com.brainshare.an.service.IAnMechanismMemberService;
import com.brainshare.common.core.domain.AjaxResult;
import com.brainshare.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import static com.brainshare.common.config.WeixinConfig.appid;
import static com.brainshare.common.config.WeixinConfig.secret;

/**
 * 机构下推广成员Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-05
 */
@Service
public class AnMechanismMemberServiceImpl implements IAnMechanismMemberService {
    @Autowired
    private AnMechanismMemberMapper anMechanismMemberMapper;
    @Value("${ruoyi.profile}")
    private String rootPath;

    @Override
    public AnMechanismMember createQrCode(AnMechanismMember anMechanismMember) {
        AnMechanismMember addMechanismMember = new AnMechanismMember();
        addMechanismMember.setMechanismId(anMechanismMember.getMechanismId());
        addMechanismMember.setMemberName(anMechanismMember.getMemberName());
        List<AnMechanismMember> existMechanismMembers = selectAnMechanismMemberList(addMechanismMember);
        if (existMechanismMembers.size() == 0) {
            //生成随机二维码，看是否有重复的，没有才插入
            String randomCode = randomCode("");
            addMechanismMember.setPromotionCode(randomCode);
            String fileName = (DateUtils.getNowDate().getTime() * 1000) + "";
            String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            String tokenStr = HttpUtil.get(tokenUrl);
            String access_token = JSONObject.parseObject(tokenStr).getString("access_token");
            String accessUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            JSONObject reqObj = new JSONObject();
            reqObj.put("page", "pages/index/index");
            reqObj.put("scene", "PromotionCode=" + addMechanismMember.getPromotionCode());
            reqObj.put("check_path", false);
            //默认打开正式版,体验版  trial
            reqObj.put("env_version", "release");
            HttpRequest post = HttpUtil.createPost(accessUrl);
            post.body(reqObj.toJSONString());
            HttpResponse execute = post.execute();
            FileUtil.writeBytes(execute.bodyBytes(), rootPath + "/images/qrcode/" + fileName + ".jpg");
//            QRCodeUtil.zxingCodeCreate(randomCode, 300, 300, rootPath + "/images/qrcode/" + fileName + ".jpg", "jpg");
            addMechanismMember.setPromotionCodeImg("/an-media/images/qrcode/" + fileName + ".jpg");
            addMechanismMember.setWechatUserId(anMechanismMember.getWechatUserId());
            addMechanismMember.setCreateBy("admin");
            addMechanismMember.setCreateTime(DateUtils.getNowDate());
            insertAnMechanismMember(addMechanismMember);
            return addMechanismMember;
        }
        return null;
    }

    private synchronized String randomCode(String randomString) {
        if ("".equals(randomString)) {
            String randomNewString = RandomUtil.randomString(4);
            randomString = randomNewString.toUpperCase();
        }
        AnMechanismMember queryObj = new AnMechanismMember();
        queryObj.setPromotionCode(randomString);
        List<AnMechanismMember> members = selectAnMechanismMemberList(queryObj);
        String result = "";
        if (members.size() > 0) {
            String randomNewString = RandomUtil.randomString(4);
            randomNewString = randomNewString.toUpperCase();
            result = randomCode(randomNewString);
        } else {
            result = randomString;
        }
        return result;
    }

    /**
     * 查询机构下推广成员
     *
     * @param mechanismMemberId 机构下推广成员主键
     * @return 机构下推广成员
     */
    @Override
    public AnMechanismMember selectAnMechanismMemberByMechanismMemberId(Long mechanismMemberId) {
        return anMechanismMemberMapper.selectAnMechanismMemberByMechanismMemberId(mechanismMemberId);
    }

    /**
     * 查询机构下推广成员列表
     *
     * @param anMechanismMember 机构下推广成员
     * @return 机构下推广成员
     */
    @Override
    public List<AnMechanismMember> selectAnMechanismMemberList(AnMechanismMember anMechanismMember) {
        return anMechanismMemberMapper.selectAnMechanismMemberList(anMechanismMember);
    }

    /**
     * 新增机构下推广成员
     *
     * @param anMechanismMember 机构下推广成员
     * @return 结果
     */
    @Override
    public int insertAnMechanismMember(AnMechanismMember anMechanismMember) {
        anMechanismMember.setCreateTime(DateUtils.getNowDate());
        return anMechanismMemberMapper.insertAnMechanismMember(anMechanismMember);
    }

    /**
     * 修改机构下推广成员
     *
     * @param anMechanismMember 机构下推广成员
     * @return 结果
     */
    @Override
    public int updateAnMechanismMember(AnMechanismMember anMechanismMember) {
        anMechanismMember.setUpdateTime(DateUtils.getNowDate());
        return anMechanismMemberMapper.updateAnMechanismMember(anMechanismMember);
    }

    /**
     * 批量删除机构下推广成员
     *
     * @param mechanismMemberIds 需要删除的机构下推广成员主键
     * @return 结果
     */
    @Override
    public int deleteAnMechanismMemberByMechanismMemberIds(Long[] mechanismMemberIds) {
        return anMechanismMemberMapper.deleteAnMechanismMemberByMechanismMemberIds(mechanismMemberIds);
    }

    /**
     * 删除机构下推广成员信息
     *
     * @param mechanismMemberId 机构下推广成员主键
     * @return 结果
     */
    @Override
    public int deleteAnMechanismMemberByMechanismMemberId(Long mechanismMemberId) {
        return anMechanismMemberMapper.deleteAnMechanismMemberByMechanismMemberId(mechanismMemberId);
    }
}
